import { defineStore } from 'pinia'
import { doctorApi, wxApi } from '@/api/index'
import { useRouter } from 'vue-router'
import Qs from 'qs'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('wxUserInfo') || '{}'),
    hospital: JSON.parse(localStorage.getItem('hospital') || '{}')
  }),

  actions: {
    // 登录获取token
    async login(loginForm) {
      try {
        const router = useRouter()
        // const params = new URLSearchParams();
        const params = {
          ...loginForm,
          grant_type: 'password',
          scope: 'server',
          type: 'wechat-report',
        }
        // 1. 获取登录token
        const res = await doctorApi.getLoginToken(params)
        
        if (res.code !== 200) {
          throw new Error(res.message || '登录失败')
        }

        // 2. 保存token
        this.token = res.data.access_token
        localStorage.setItem('token', this.token)

        // 3. 调用connection接口
        const connectionRes = await doctorApi.getLoginConnection()
        if (connectionRes.code !== 200) {
          throw new Error(connectionRes.message || 'connection失败')
        }

        // 4. 获取用户信息
        const userInfoRes = await wxApi.getWxUserInfo()
        if (userInfoRes.code === 200) {
          this.userInfo = userInfoRes.data
          localStorage.setItem('wxUserInfo', JSON.stringify(userInfoRes.data))

          // 5. 获取医院信息
          const hospitalRes = await wxApi.getHospitalInfo({ 
            openid: this.userInfo.openid, 
            appid: this.userInfo.wxAppId 
          })
          
          if (hospitalRes.code === 200) {
            this.hospital = hospitalRes.data
            localStorage.setItem('hospital', JSON.stringify(hospitalRes.data))
            
            // 6. 跳转到医生列表页
            router.push('/doctor/list')
            return { success: true }
          }
        }

        throw new Error('获取用户信息失败')

      } catch (error) {
        console.error('登录流程失败:', error)
        return {
          success: false,
          message: error.message || '登录失败'
        }
      }
    },

    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = {}
      this.hospital = {}
      localStorage.removeItem('token')
      localStorage.removeItem('wxUserInfo')
      localStorage.removeItem('hospital')
    }
  }
})